package com.td.core.obj.bullet;

import java.util.LinkedList;
import java.util.Random;

import com.td.core.obj.TDObject;
import com.td.core.obj.TDPoint;
import com.td.core.obj.TDRealObject;
import com.td.core.obj.movement.Moveable;
import com.td.core.obj.movement.Movement;
import com.td.core.obj.unit.Unit;
import com.td.core.obj.utils.PointConverter;
import com.td.core.obj.utils.TDVector;

public class Bullet extends TDRealObject implements Moveable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private transient Movement movement;
	private float speed = 10;
	private int size = 5;
	private int minDamage;
	private int maxDamage;
	private int splash;
	private Unit attackedUnit;
	
	private boolean goal;
	private transient TDVector target;
	
	public Bullet(int x, int y) {
		super(x, y);
		// TODO Auto-generated constructor stub
	}
	
	public Bullet(TDPoint position, Unit unit) {
		this(position.getX(), position.getY());
		
		this.attackedUnit = unit;
		this.target = unit.getRealPosition();
		LinkedList<TDVector> path = new LinkedList<TDVector>();
		path.add(this.target);
		movement = new Movement(speed, path);
		movement.setStepScale(360);
		movement.setMinDistanceToNextPoint(1);
	}
	
	public Bullet(Bullet bullet) {
		this(bullet.getPosition().getX(), bullet.getPosition().getY());
		this.setRealPosition(new TDVector(bullet.getRealPosition()));
	}
	
	@Override
	public void move() {
		
		if(movement == null)
			return;
		
		
		TDVector mov = movement.calculate(getRealPosition());
		if(mov != null) {
			
			setRealPosition(getRealPosition().add(mov));
		   	setPosition(PointConverter.toTDPoint(getRealPosition()));
		   	
		   	if(getRealPosition().distance(target) <= speed) {
		   		
		   		attackedUnit.deacreaseLife(getDamage());
		   		goal = true;
		   	}
			
		}
		
	}
	
	public boolean isGoal() {
		return goal;
	}
	
	@Override
	public synchronized void copyTo(TDObject obj) {
		synchronized (obj) {
			
			if(obj instanceof Bullet) {
			
				Bullet b = (Bullet)obj;
				
				b.setPosition(this.getPosition());
				b.setRealPosition(new TDVector(this.getRealPosition()));
			}
			
		}
		
	}

	@Override
	public TDObject getCopy() {
		return new Bullet(this);
	}

	public int getSize() {
		return size;
	}
	
	public int getDamage() {
		Random r = new Random();
		int d = r.nextInt(maxDamage - minDamage);
		
		return d + minDamage;	
	}
	
	public Unit getAttackedUnit() {
		return attackedUnit;
	}

	public int getSplash() {
		return splash;
	}

	public void setMinDamage(int minDamage) {
		this.minDamage = minDamage;
	}

	public void setMaxDamage(int maxDamage) {
		this.maxDamage = maxDamage;
	}

	public void setSplash(int splash) {
		this.splash = splash;
	}
	
	

	

}
